{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## TF-IDF 算法示例"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 引入依赖"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 定于数据和预处理"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'The', 'cat', 'deb', 'dog', 'kness', 'my', 'on', 'sat'}"
      ]
     },
     "execution_count": 24,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "docA = \"The cat sat on my deb\"\n",
    "docB = \"The dog sat on my kness\"\n",
    "\n",
    "bowA = docA.split(\" \")\n",
    "bowB = docB.split(\" \")\n",
    "\n",
    "wordSet = set(bowA).union(set(bowB))\n",
    "\n",
    "wordSet"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 进行词数统计"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>The</th>\n",
       "      <th>cat</th>\n",
       "      <th>deb</th>\n",
       "      <th>dog</th>\n",
       "      <th>kness</th>\n",
       "      <th>my</th>\n",
       "      <th>on</th>\n",
       "      <th>sat</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   The  cat  deb  dog  kness  my  on  sat\n",
       "0    1    1    1    0      0   1   1    1\n",
       "1    1    0    0    1      1   1   1    1"
      ]
     },
     "execution_count": 35,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 用统计字典来保存词出现的次数\n",
    "wordDictA = dict.fromkeys(wordSet, 0)\n",
    "wordDictB = dict.fromkeys(wordSet, 0)\n",
    "\n",
    "\n",
    "# 遍历文档，统计词数\n",
    "for word in bowA:\n",
    "    wordDictA[word] += 1\n",
    "for word in bowB:\n",
    "    wordDictB[word] += 1\n",
    "\n",
    "pd.DataFrame([wordDictA, wordDictB])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 计算词频TF"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'The': 0.16666666666666666,\n",
       " 'cat': 0.16666666666666666,\n",
       " 'deb': 0.16666666666666666,\n",
       " 'dog': 0.0,\n",
       " 'kness': 0.0,\n",
       " 'my': 0.16666666666666666,\n",
       " 'on': 0.16666666666666666,\n",
       " 'sat': 0.16666666666666666}"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def computeTF(wordDict, bow):\n",
    "    # 用一个字典对象记录tf, 把所有的词对应在bow 文档中的tf 算出来\n",
    "    tfDict = {}\n",
    "    nbowCount = len(bow)\n",
    "    \n",
    "    for word, count in wordDict.items():\n",
    "        tfDict[word] = count / nbowCount\n",
    "        \n",
    "    return tfDict\n",
    "\n",
    "tfA = computeTF(wordDictA, bowA)\n",
    "tfB = computeTF(wordDictB, bowB)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 计算逆文档频率IDF"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'The': 0.0,\n",
       " 'cat': 0.17609125905568124,\n",
       " 'deb': 0.17609125905568124,\n",
       " 'dog': 0.17609125905568124,\n",
       " 'kness': 0.17609125905568124,\n",
       " 'my': 0.0,\n",
       " 'on': 0.0,\n",
       " 'sat': 0.0}"
      ]
     },
     "execution_count": 36,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def computeIDF(wordDictList):\n",
    "    # 用一个字典对象保存idf 结果， 每个词为key\n",
    "    idfDict = dict.fromkeys(wordDictList[0], 0)\n",
    "    N = len(wordDictList)\n",
    "    import math\n",
    "    \n",
    "    for wordDict in wordDictList:\n",
    "        # 遍历字典中的每个词汇\n",
    "        for word, count in wordDict.items():\n",
    "            if count > 0:\n",
    "                # 先把Ni 增加1 ，存入到idfDict\n",
    "                idfDict[word] += 1\n",
    "                \n",
    "    # 已经得到所有词汇i对应的Ni, 现在根据公式把他替换为idf 值\n",
    "    for word, ni in idfDict.items():\n",
    "        idfDict[word] = math.log10((N+1)/(ni+1))\n",
    "            \n",
    "    return idfDict\n",
    "    \n",
    "idfs = computeIDF([wordDictA, wordDictB])\n",
    "idfs"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 计算TF-IDF"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>The</th>\n",
       "      <th>cat</th>\n",
       "      <th>deb</th>\n",
       "      <th>dog</th>\n",
       "      <th>kness</th>\n",
       "      <th>my</th>\n",
       "      <th>on</th>\n",
       "      <th>sat</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>0.0</td>\n",
       "      <td>0.029349</td>\n",
       "      <td>0.029349</td>\n",
       "      <td>0.000000</td>\n",
       "      <td>0.000000</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>0.0</td>\n",
       "      <td>0.000000</td>\n",
       "      <td>0.000000</td>\n",
       "      <td>0.029349</td>\n",
       "      <td>0.029349</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   The       cat       deb       dog     kness   my   on  sat\n",
       "0  0.0  0.029349  0.029349  0.000000  0.000000  0.0  0.0  0.0\n",
       "1  0.0  0.000000  0.000000  0.029349  0.029349  0.0  0.0  0.0"
      ]
     },
     "execution_count": 42,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def computeTFIDF(tf, idfs):\n",
    "    tfidf = {}\n",
    "    for word, tfval in tf.items():\n",
    "        tfidf[word] = tfval * idfs[word]\n",
    "        \n",
    "    return tfidf\n",
    "\n",
    "tfidfA = computeTFIDF(tfA, idfs)\n",
    "tfidfB = computeTFIDF(tfB, idfs)\n",
    "\n",
    "pd.DataFrame([tfidfA, tfidfB])"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.2"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
